package com.rongke.web.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.commons.PageDto;
import com.rongke.enums.FileType;
import com.rongke.model.*;
import com.rongke.service.RefuseAreaService;
import com.rongke.service.UserAuthService;
import com.rongke.service.UserIdentityService;
import com.rongke.service.UserService;
import com.rongke.utils.PubLib;
import com.rongke.web.config.Config;
import com.rongke.web.ud.UDAPI;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @version : Ver 1.0
 * @UserIdentityController
 * @Controller
 */
@RestController
@RequestMapping(value = "/api/userIdentity")
@Transactional
@CrossOrigin
public class UserIdentityController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private UserIdentityService userIdentityService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserAuthService userAuthService;
    @Autowired
    public Config config;
    @Autowired
    private RefuseAreaService refuseAreaService;
    /**
     * @param userIdentity
     * @return 返回值JsonResp
     * @添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addUserIdentity(@RequestBody UserIdentity userIdentity,HttpServletRequest request ) throws IOException {
        log.debug("添加");
//        User user = userService.findLoginUser();
        User user = userService.selectById(userIdentity.getUserId());
        userIdentity.setUserId(user.getId());
        userIdentity.setStatus(1);
        String frontF = userIdentity.getIdentityFront();
        String frontB = userIdentity.getIdentityBack();
        String frontR = userIdentity.getFaceUrl();
        String []  s = new String[]{frontB,frontF,frontR};
//        s[0] = frontB;
//        s[1] = frontF;
//        s[2] = frontR;
/*        for(int i = 0; i < s.length; i++){
            byte[] bytes = Base64.decodeBase64(s[i]);
            File file = new File("xxx");
            OutputStream output = new FileOutputStream(file);
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
            bufferedOutput.write(bytes);
            String[] paths = FileType.getPath(FileType.OTHER, 1, request);
            String fileName = UUID.randomUUID().toString();
            String path = paths[0] + File.separator + fileName + ".jpg";
            File saveFile = new File(path);
            FileInputStream in_file = new FileInputStream(file);
            MultipartFile multi = new MockMultipartFile(fileName + ".jpg", in_file);
            multi.transferTo(saveFile);
            String savePath = config.getUploadHost(request, null, saveFile.getParentFile().getName(), saveFile.getName());

            if(i == 0){
                userIdentity.setIdentityBack(savePath);
            }else if (i == 1){
                userIdentity.setIdentityFront(savePath);
            }else if (i == 2){
                userIdentity.setFaceUrl(savePath);
            }
            bufferedOutput.close();
            in_file.close();
        }*/
        //按照地区拒绝
 /*       String idcard = userIdentity.getIdentityNum();
        idcard = idcard.substring(0,6);
        Map cMap = new HashMap();
        List<RefuseArea> list = refuseAreaService.selectByMap(cMap);
        for(RefuseArea a:list){
            String code = a.getAreaCode().substring(0,6);
            if(code.equals(idcard)){
                user.setStatus(5);
                userService.updateById(user);
                return JsonResp.fa("验证失败");
            }
        }*/
        userIdentityService.insert(userIdentity);
        EntityWrapper<UserAuth> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id",user.getId());
        UserAuth userAuth = userAuthService.selectOne(wrapper);
        userAuth.setIdentityAuth(1);
        userAuthService.updateById(userAuth);
        return JsonResp.ok(userIdentity);
    }



    /**
     * @param
     * @return 返回值JsonResp
     * @人脸对比认证
     */
    @RequestMapping(value = "/getPhotoPass", method = RequestMethod.GET)
    public JsonResp getPhotoPass(String session_id,String facePhoto,String param) throws IOException {
        log.debug("人脸对比认证");
        String url = facePhoto+"&param="+param;
        log.info("sessionId==========="+url);
        JSONObject jsonObject = UDAPI.faceCompare(session_id,url);
        log.info("+++++++++++++++++"+jsonObject);
        Map map = (Map)jsonObject.get("result");
        String result = map.get("success").toString();
        if(result.equals("true")){
            Map data = (Map)jsonObject.get("data");
            String similarity = data.get("similarity").toString();
            Object thresholds = data.get("thresholds");
            JSONObject thresholds1 = JSONObject.parseObject(JSONObject.toJSONString(thresholds));
            if (Double.valueOf(similarity)>Double.valueOf(thresholds1.get("1e-4").toString())){
                return JsonResp.ok();
            }else{
                return JsonResp.fa("您的人脸匹配度不够高！");
            }
        }else{
            return JsonResp.fa(map.get("message").toString());
        }
    }
    /**
     * @param
     * @return 返回值JsonResp
     * @实名认证
     */
    @RequestMapping(value = "/getIdCardPass", method = RequestMethod.GET)
    public JsonResp getIdCardPass(String id_number, String id_name) throws IOException {
        log.debug("实名认证");
        JSONObject jsonObject = UDAPI.idCardVerify(id_number,id_name);
        log.info("+++++++++++++++++"+jsonObject);
        Map map = (Map)jsonObject.get("result");
        String result = map.get("success").toString();
        if(result.equals("true")){
            Map data = (Map)jsonObject.get("data");
            if(data.get("verify_status").toString().equals("1")){
                log.info("verify_status"+data.get("verify_status").toString());
                return JsonResp.ok(data.get("session_id").toString());
            }else{
                return JsonResp.fa("身份证信息不一致！");
            }
        }else{
            return JsonResp.fa(map.get("message").toString());
        }
    }
    private  static void uploadPhoto(File file,HttpServletRequest request) throws IOException {

    }
    /**
     * @param userIdentity
     * @return 返回值JsonResp
     * @修改
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateUserIdentity(@RequestBody UserIdentity userIdentity) {
        log.debug("修改");
        userIdentityService.updateById(userIdentity);
        return JsonResp.ok(userIdentity);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectUserIdentity(Long id) {
        log.debug("查找");
        UserIdentity userIdentity = userIdentityService.selectById(id);
        return JsonResp.ok(userIdentity);
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @修改
     */
    @RequestMapping(value = "/findByPage", method = RequestMethod.GET)
    public JsonResp findByPage(Integer pageNo, Integer pageSize,String realName,Integer status,String phone){
        log.debug("分页查询认证信息");

        Map<String,Object> map = new HashMap<>();
        map.put("pageNo",(pageNo-1)*pageSize);
        map.put("pageSize",pageSize);
        map.put("phone",phone);
        map.put("realName",realName);
        map.put("status",status);
        Integer total = userIdentityService.selectCount(map);
        List<UserIdentity> list = userIdentityService.selectByPage(map);
        PageDto pageDto = new PageDto(pageNo,pageSize,list,total);

        return JsonResp.ok(pageDto);
    }

    /**
     * 根据id查询身份证认证信息
     * @param id
     * @return
     */
  @RequestMapping(value = "/selectOneIdentity",method = RequestMethod.GET)
   public JsonResp selectOneIdentity(Long id){



      UserIdentity  userIdentity=userIdentityService.selectById(id);
      User user=userService.selectById(userIdentity.getUserId());
      userIdentity.setUser(user);

     return  JsonResp.ok(userIdentity);
   }

/**
 * 根据id查询身份证认证信息
 * @param id
 * @return
 */
    @RequestMapping(value = "/selectOneDetailsByUserId",method = RequestMethod.GET)
    public JsonResp selectOneDetailsByUserId(String id){



        UserIdentity  userIdentity=userIdentityService.selectOneDetailsByUserId(id);
      //  User user=userService.selectById(userIdentity.getUserId());
        //userIdentity.setUser(user);

        return  JsonResp.ok(userIdentity);
    }

}
